// 连接服务端
function connect() {
    // 创建websocket
    ws = new WebSocket("ws://"+document.domain+":7272");
    ws.onopen = onopen;

    // 当有消息时根据消息类型显示不同信息
    ws.onmessage = onmessage;
    ws.onclose = function() {
        console.log("连接关闭，定时重连");
        connect();
    };
    ws.onerror = function() {
        console.log("出现错误");
    };
}

//客服登录
function start()
{
    var i=0;
    var arr = new Array();
    if(!user_name || user_name=='null'){
        user_name = prompt('输入你的客服名称：', '');
    }else{
        //ajax查询是否存在该客服
        $("#userlist1 li>a").each(function(){
            arr[i] = $.trim($(this).text());
            i++;
        });
        if($.inArray(user_name, arr) == -1){  //查询客服是否存在
            alert('客服不存在');
            start();
        }else{
            if(!user_pwd || user_pwd=='null'){
                user_pwd = prompt('输入你的客服名称：', '');
            }else{
                $.post(cheakpwd_link,{user_name:user_name,user_pwd:user_pwd},function(data){
                    if(!data){
                        alert('客服密码错误');
                        window.location.reload();
                    }else{ //客服登录成功
                        var login_data = '{"type":"kefu_login","client_name":"'+user_name.replace(/"/g, '\\"')+'","room_id":"'+room_id+'"}';
                        //console.log("websocket握手成功，发送登录数据:"+login_data);
                        ws.send(login_data);
                    }
                });
            }
        }
    }
}

// 连接建立时发送登录信息
function onopen()
{
    if(kefu != ''){
        start();
    }else{
        if(!name) {
            name = prompt('输入你的名字：', '');
            if(!name || name=='null'){
                name = '游客';
            }
        }
        if(user_id == ''){
            // 登录，发送名字、房间id。默认只有一个房间 id为1
            var login_data = '{"type":"login","client_name":"'+name.replace(/"/g, '\\"')+'","room_id":"'+room_id+'"}';
            ws.send(login_data);  //发送登录的数据 触发回调
        }else{
            // 登录，发送名字、房间id。默认只有一个房间 id为1
            var login_data = '{"type":"user_id_login","user_id":'+user_id+',"client_name":"'+name.replace(/"/g, '\\"')+'","room_id":"'+room_id+'"}';
            ws.send(login_data);  //发送登录的数据 触发回调
        }

    }
}

// 服务端发来消息时
function onmessage(e)
{
    var data = eval("("+e.data+")");
    switch(data['type']){
        // 服务端ping客户端
        case 'ping':
            ws.send('{"type":"pong"}');  //服务端ping 客户端
            break;
        // 登录 更新用户列表
        case 'login':
            //{"type":"login","client_id":xxx,"client_name":"xxx","client_list":"[...]","time":"xxx"}
            say(data['client_id'], data['client_name'],  data['client_name']+' 加入了聊天室', data['time']);
            if(data['client_list']) {
                client_list = data['client_list'];
            } else {
                client_list[data['client_id']] = data['client_name'];
            }
            flush_client_list();
            console.log(data['client_name']+"登录成功");
            break;
        case 'kefu_login':
            login_msg(data['client_id'], data['client_name'], data['content'], data['time']);
            flush_client_list();
            //console.log('登录成功');
            break;
        case 'kefu_say':
            kefu_say(data['client_id'], data['client_name'], data['content'], data['time']);
            break;
        // 发言
        case 'say':
            //{"type":"say","from_client_id":xxx,"to_client_id":"all/client_id","content":"xxx","time":"xxx"}
            say(data['from_client_id'], data['from_client_name'], data['content'], data['time']);
            break;
        // 用户退出 更新用户列表
        case 'logout':
            //{"type":"logout","client_id":xxx,"time":"xxx"}
            say(data['from_client_id'], data['from_client_name'], data['from_client_name']+' 退出了', data['time']);
            delete client_list[data['from_client_id']];
            flush_client_list();
    }
}

//客服say
function kefu_say(client_id, client_name, content, time){
    $("#dialog").append('<div class="speech_item"><img style="width: 44px;height: 44px;" src="http://www.spcmf.cn/img/'+ img +'" class="user_icon" /> '+client_name+'客服<br> '+time+'<div style="clear:both;"></div><p class="triangle-isosceles top">'+content+'</p> </div>');
}

// 发言
function say(from_client_id, from_client_name, content, time){
    $("#dialog").append('<div class="speech_item"><img style="width: 44px;height: 44px;" src="http://www.spcmf.cn/img/'+ img +'" class="user_icon" /> '+from_client_name+' <br> '+time+'<div style="clear:both;"></div><p class="triangle-isosceles top">'+content+'</p> </div>');
}

// 客服登录
function login_msg(client_id, client_name, content, time){
    $("#dialog").append('<div class="speech_item"><img style="width: 44px;height: 44px;" src="http://www.spcmf.cn/img/'+ img +'" class="user_icon" /> '+client_name+'客服 <br> '+time+'<div style="clear:both;"></div><p class="triangle-isosceles top">"'+client_name+'"为您服务！</p> </div>');
}

// 提交对话
function onSubmit() {
    var input = document.getElementById("textarea");
    var to_client_id = $("#client_list option:selected").attr("value");
    var to_client_name = $("#client_list option:selected").text();
    ws.send('{"type":"say","to_client_id":"'+to_client_id+'","to_client_name":"'+to_client_name+'","content":"'+input.value.replace(/"/g, '\\"').replace(/\n/g,'\\n').replace(/\r/g, '\\r')+'"}');
    input.value = "";
    input.focus();
}
//和客服之间的聊天提交
function onSubmit1() {
    var input = document.getElementById("textarea");
    var to_client_id = $("#client_list option:selected").attr("value");
    var to_client_name = $("#client_list option:selected").text();
    ws.send('{"type":"kefu_say","to_client_id":"'+to_client_id+'","to_client_name":"'+to_client_name+'","content":"'+input.value.replace(/"/g, '\\"').replace(/\n/g,'\\n').replace(/\r/g, '\\r')+'"}');
    input.value = "";
    input.focus();
}


// 刷新用户列表框
function flush_client_list(){
    var userlist_window = $("#userlist");
    var client_list_slelect = $("#client_list");
    userlist_window.empty();
    client_list_slelect.empty();
    userlist_window.append('<h4>在线用户</h4><ul>');
    client_list_slelect.append('<option value="all" id="cli_all">所有人</option>');
    for(var p in client_list){
        userlist_window.append('<li id="'+p+'">'+client_list[p]+'</li>');
        client_list_slelect.append('<option value="'+p+'">'+client_list[p]+'</option>');
    }
    $("#client_list").val(select_client_id);
    userlist_window.append('</ul>');
}

